﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Controls;

namespace Phone.Framework.Behaviors
{
    public class AppBarButtonEnableBehavior
    {


        public static string GetButtonName(DependencyObject obj)
        {
            return (string)obj.GetValue(ButtonNameProperty);
        }

        public static void SetButtonName(DependencyObject obj, string value)
        {
            obj.SetValue(ButtonNameProperty, value);
        }

        public static readonly DependencyProperty ButtonNameProperty =
            DependencyProperty.RegisterAttached("ButtonName", typeof(string), typeof(AppBarButtonEnableBehavior),
            new PropertyMetadata(string.Empty, (sender, arg) =>
            {
                var element=sender as PhoneApplicationPage;
                if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(element)) return;
                PhoneApplicationService.Current.State[Constant.CurrentEnableAppBarButton] = null;
                if (arg.NewValue == null) return;
                var page = sender as PhoneApplicationPage;
                page.Loaded += new RoutedEventHandler(page_Loaded);

            }));

        static void page_Loaded(object sender, RoutedEventArgs e)
        {
            var page = sender as PhoneApplicationPage;

            PhoneApplicationService.Current.State[Constant.CurrentEnableAppBarButton] = page.ApplicationBar.FindButton(GetButtonName(page));

            page.Loaded -= new RoutedEventHandler(page_Loaded);
        }
    }

    public class AppBarButton
    {
        public static void EnableAppBarButton()
        {
            var btn = PhoneApplicationService.Current.State[Constant.CurrentEnableAppBarButton] as ApplicationBarIconButton;
            if (btn != null)
                btn.IsEnabled = true;
        }

        public static void DisableAppBarButton()
        {
            var btn = PhoneApplicationService.Current.State[Constant.CurrentEnableAppBarButton] as ApplicationBarIconButton;
            if (btn != null)
                btn.IsEnabled = false;
        }

        public static void Auto(Action action)
        {
            var btn = PhoneApplicationService.Current.State[Constant.CurrentEnableAppBarButton] as ApplicationBarIconButton;
            if (btn != null)
            {
                btn.IsEnabled = false;
                action();
                btn.IsEnabled = true;
            }
        }
    }
}
